package com.luoqiz.es.transport.config;

import java.net.InetAddress;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@PropertySources(value = { @PropertySource("classpath:es.properties") })
public class ESTransportConfig {
	private static final String CLUSTER_NODES_SPLIT_SYMBOL = ",";
	private static final String HOST_PORT_SPLIT_SYMBOL = ":";
	private int poolSize = 8;

	@Autowired
	private Environment environment;

	@Bean
	public TransportClient getTransportClient() {
		log.info("elasticsearch init.");
		String clusterName = environment.getRequiredProperty("elasticsearch.cluster-name");
		if (StringUtils.isEmpty(clusterName)) {
			throw new RuntimeException("elasticsearch.cluster-name is empty.");
		}
		String clusterNodes = environment.getRequiredProperty("elasticsearch.cluster-nodes");
		if (StringUtils.isEmpty(clusterNodes)) {
			throw new RuntimeException("elasticsearch.cluster-nodes is empty.");
		}
		String customPoolSize = environment.getRequiredProperty("elasticsearch.pool-size");
		if (StringUtils.isEmpty(customPoolSize)) {
			poolSize = Integer.parseInt(customPoolSize);
		}
		log.info("elasticsearch.cluster-nodes:" + clusterNodes);
		try {
			// 配置信息
			Settings settings = Settings.builder().put("cluster.name", clusterName.trim())// 集群名字
					.put("client.transport.sniff", true)// 增加嗅探机制，找到ES集群
					.put("thread_pool.search.size", poolSize)// 增加线程池个数，暂时设为5
					.build();
			TransportClient transportClient = new PreBuiltTransportClient(settings);
			String[] clusterNodeArray = clusterNodes.trim().split(CLUSTER_NODES_SPLIT_SYMBOL);
			for (String clusterNode : clusterNodeArray) {
				String[] clusterNodeInfoArray = clusterNode.trim().split(HOST_PORT_SPLIT_SYMBOL);
				TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(clusterNodeInfoArray[0]),
						Integer.parseInt(clusterNodeInfoArray[1]));
				transportClient.addTransportAddress(transportAddress);
			}
			log.info("elasticsearch init success.");
			return transportClient;
		} catch (Exception e) {
			throw new RuntimeException("elasticsearch init fail.");
		}
	}
}